#!/user/bin/env python3
# -*- coding: utf-8 -*-
# -- anth bluedolphi ---

import datetime

from requests.structures import CaseInsensitiveDict

from spider.AIYZ.AIYZSpirder import AIYZBaseSpider
from util.EncodeingUtil import url_encode
from util.GoogleCode import calGoogleCode

class AIYZAdminSpider(AIYZBaseSpider):
    host = "%s"
    account = ""
    password = ""
    token = '';
    enterpriseProcessStatusStr = ["已禁用","对接中","等待上线","已上线","洽谈中","暂停"]
    notDealEnterpriseIds = None #["已禁用","对接中","等待上线","洽谈中","暂停"] 的企业

    def __init__(self, account, passwrod,secretKey,host="admin.aiyouzhan.cn",token=None):
        super().__init__(self.host)
        self.host = host
        self.header = {
            'Host': self.host,
            'Connection': 'keep-alive',
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Origin': 'https://%s' % (self.host),
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
            'Referer': 'https://%s/index.html' % (self.host),
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
        }
        if token is not None:
            self.token = token
            self.header.update([("Authorization", "Bearer %s" % self.token)])
            return

        self.loginUrl = "https://%s/api/admin/admin/login" % (self.host);
        self.randcodeUrl = 'https://%s/api/common/getImageCaptche'  % (self.host);
        self.account = account
        self.password = passwrod
        self.secretKey =secretKey
        #self.login()

    def isLogined(self):
        if str(self.token).__eq__(""):
            return False
        url="https://%s/api/enterprise/admin/enterprise/page-list?page=1&size=1&token=%s" % (self.host,self.token)

        resp = self.get(url,self.header)
        if str(resp.text).__contains__('"code":1,'):
            return True

        return False;

    def login(self):

        if  self.isLogined() :
            return

        imgToken, code = self.getRandCode(self.host)
        print(code)
        data = url_encode({
            'username': self.account,
            'password': self.password,
            'googleCode': calGoogleCode(self.secretKey),
            'code': code,
            'imgToken': imgToken,
        })
        print(self.loginUrl)
        print(self.header)
        json1 = self.getJsonByUrlWithPost(self.loginUrl, data=data, header=self.header)
        if (json1 is None):
            print("login err ")
        else:
            self.token = json1['data']['token']
            print("token = ", self.token)
            self.header.update([("Authorization", "Bearer %s" % self.token)])

    def setToken(self,token):
        self.token = token
        self.header.update([("Authorization", "Bearer %s" % self.token)])




    def getEnterprisesInfo(self,enterpriseName='',status=''):
        """
        取得油站企业信息表
        :param enterpriseName:
        :param status:
        :return:{ "id": "X", "name": "X", "type": 2, "legalPerson": "", "licenseNo": null, "organizationNo": null, "contact": "张静", "phone": "", "address": "", "logoUrl": "", "status": 3, "csUserName": "XXXX", "bmUserName": "", "enterpriseCode": "X", "yktEnterpriseSn": null }
        """
        baseUrl ="https://%s/api/enterprise/admin/enterprise/page-list?status=%s&enterpriseName=%s&page=1&size=1&token=%s" % (self.host,status,enterpriseName,self.token)
        list =self.get(baseUrl)
        return list

    def getNotDealEnterpriseIds(self):
        if self.notDealEnterpriseIds is not None:
            return self.notDealEnterpriseIds;
        self.notDealEnterpriseIds=[]
        for statusStr in self.enterpriseProcessStatusStr :
            if statusStr =="已上线" : continue
            list = self.getEnterprisesInfo(status=self.enterpriseProcessStatusStr.index(statusStr))
            for o in list:
                print("id=%s name=%s 放入不显示库" % (o['id'],o['name']))
                self.notDealEnterpriseIds.append(o['id'])
        return self.notDealEnterpriseIds

    def printEnterpriseProcessStatusInfo(self):
        """
            打印所有油站企业状态 数量
        """
        enterpriseName = ''

        for statusStr in self.enterpriseProcessStatusStr:
            status =self.enterpriseProcessStatusStr.index(statusStr)
            baseUrl = "https://%s/api/enterprise/admin/enterprise/page-list?status=%s&enterpriseName=%s&token=%s" % (
            self.host,status, enterpriseName, self.token)
            total =self.getTotolRowsFromUrl(baseUrl)
            print("%s  共%s家;" % (statusStr,total))

    def getAllEnterpriseProcessStatusInfo(self):
        """
            打印所有油站企业状态 数量
        """
        enterpriseName = ''
        list={}
        for statusStr in self.enterpriseProcessStatusStr:
            status =self.enterpriseProcessStatusStr.index(statusStr)
            baseUrl = "https://%s/api/enterprise/admin/enterprise/page-list?status=%s&enterpriseName=%s&token=%s" % (
            self.host,status, enterpriseName, self.token)
            total =self.getTotolRowsFromUrl(baseUrl)
            print("%s  共%s家;" % (statusStr,total))
            list[statusStr]=total
        return list




    def getEnterpriseProcessStatusInfoBystastionName(self,status,enterpriseName=""):
        baseUrl = "https://%s/api/enterprise/admin/enterprise/page-list?status=%s&enterpriseName=%s&token=%s" % (self.host,
            status, enterpriseName, self.token)
        list =self.getRowsFromUrl(baseUrl)




    def getGasStationDateReport(self,  date, stationName, token):
        _headers = CaseInsensitiveDict([
            ('Accept', '*/*'),
            ('Accept-Encoding', 'gzip, deflate'),
            ('Accept-Language', 'zh-CN,zh;q=0.9'),
            ('Connection', 'keep-alive'),
            ('Host', '%s'),
            ("Authorization", "Bearer %s" % self.token),
            ('Origin', 'https://%s' % (self.host)),
            ('Referer', 'https://%s/index.html' % (self.host)),
            ('User-Agent', self.AGENT_STRING)])
        dateString = (date + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
        baseUrl="https://%s/api/enterprise/admin/gas-station/listCount?date=%s&stationName=%s&token=%s" % (self.host,
                 dateString, stationName, token);
        print("dateString = ", dateString)
        rows = self.getRowsFromUrl(baseUrl,5)
        return rows


    def getEnterpriseInfoByName(self,name,enterpriseId=None):
        #{'id': '', 'name': '', 'type': 2, 'legalPerson': '', 'licenseNo': None, 'organizationNo': None, 'contact': '', 'phone': '', 'address': '', 'logoUrl': '', 'status': 1, 'csUserName': '陈钦', 'bmUserName': '陈勇', 'enterpriseCode': 'dljyz', 'yktEnterpriseSn': None}
        url="https://%s/api/enterprise/admin/enterprise/page-list?status=&enterpriseName=%s&token=%s"% (self.host,name,self.token)

        rows = self.getRowsFromUrlByNoThread(baseUrl=url)
        for o in rows:
            if str(o["name"]).__eq__(name):
                if enterpriseId is None:
                    return o
                elif str(enterpriseId).__eq__(o["id"]):
                    return o
        return None

    def getEnterpriseInfoByGasStationName(self, gasStationName, gasStationId=None):
        o = self.getGastionByName(gasStationName,gasStationId)
        if o is None: return None
        return self.getEnterpriseInfoByName(o['enterpriseName'])

    def getGastionByName(self,name,gasStationId=None):
        url="https://%s/api/enterprise/admin/gas-station/page-list?status=&gasStationName=%s&enterpriseName=&token=%s" %(self.host,name,self.token)
        rows = self.getRowsFromUrlByNoThread(baseUrl=url)
        for o in rows:
            if str(o["name"]).__eq__(name):
                if gasStationId is None:
                    return o
                elif str(gasStationId).__eq__(o["id"]):
                    return o
        return None

    def getAllGasStationsInfo(self):
        '''

        :return:
        '''
        baseUrl = "https://%s/api/enterprise/admin/gas-station/page-list?status=%s&token=%s" % (self.host,
        1, self.token)
        rows = self.getRowsFromUrl(baseUrl)
        return rows


    #取得有数据的加油站列表
    def getHasDataGasStations_minTotalAmountToday(self,minTotalAmountToday=100):
        baseUrl="https://%s/api/enterprise/admin/gas-station/listCount?token=%s " % (self.host,self.token)
        pageSize = 10
        list = self.getRowsFromUrl(baseUrl,pageSize)
        list2=[]
        for o in list:
            if o["totalAmountToday"]<=minTotalAmountToday:
                continue
            list2.append(o)
        print(list2)
        return list2

    #取得有数据的加油站列表
    def getHasDataGasStations_maxTotalAmountToday(self,maxTotalAmountToday=100):
        baseUrl="https://%s/api/enterprise/admin/gas-station/listCount?token=%s " % (self.host,self.token)
        pageSize = 10
        list = self.getRowsFromUrl(baseUrl,pageSize)
        list2=[]
        for o in list:
            if o["totalAmountToday"]<=maxTotalAmountToday:
                list2.append(o)

        return list2

    def getCustomerServicerByGasStationName(self,gasStationName):
        baseUrl="https://%s/api/enterprise/admin/gas-station/page-list?status=&gasStationName=%s&enterpriseName=&token=%s" %(self.host,gasStationName,self.token)
        list = self.getRowsFromUrlByNoThread(baseUrl)

        if list is None:
            return ''
        for o in list:
            if o is not None and str(o["name"]).__eq__(gasStationName):
                print(o)
                return o["customerService"]
        return ""


    # 取得有数据的加油站列表服务员
    def getHasDataGasStationsServicer(self):
        list =self.getHasDataGasStations()
        servicers = []
        for o in list:
            customerServicer= self.getCustomerServicerByGasStationName(o["stationName"])
            #print("%s %s" %(o["stationName"],customerServicer))
            servicers.append("%s %s" %(o["stationName"],customerServicer))

        for o in servicers:
            print(o)

    def getOrderList(self,startDate,endDate,status=2,enterpriseId="",stationId=""):
        url="https://%s/api/gas/admin/orderPageList?status=%s&enterpriseId=%s&stationId=%s&startDate=%s&endDate=%s&token=%s" %(self.host,status,enterpriseId,stationId,startDate,endDate,self.token)
        list = self.getRowsFromUrl(url)
        return list

    def getHasOrderDataGasStation(self,startDate,endDate):
        list = self.getOrderList(startDate,endDate)
        list2= []
        for o in list:
            list2.append(o["stationName"])
        list = (set(list2))
        print("总共有%s家有走数据 " % len(list))
        for o in list:
            print(o)



    def get_gasStions_by_enterprise(self,id,enterpriseName):
        """
        {"id":"","enterpriseId":"","gasStationCode":"","customerService":"","customerServicePhone":"","customerServiceQrcode":"","enterpriseName":"","name":"","phone":""
        ,"captchePhone":null,"province":"","city":"","area":"","address":"","lng":,"lat":,"status":1,"distance":null,"remainSms":0,"createTime":"","captcheOpenId":null
        ,"memberUserId":null,"yktStationSn":null}
        :param id:
        :param enterpriseName:
        """
        url="https://%s/api/enterprise/admin/gas-station/page-list?status=&gasStationName=&enterpriseName=%s&token=%s" %(self.host,enterpriseName,self.token)
        rows = self.getRowsFromUrl(url)
        list = []
        for o in rows:
            if str(o["enterpriseId"]).__eq__(id):
                list.append(o)
        print(list)
        return list;


    def get_not_online_enterprises(self):
        """
{id: id:"", name: "加油站", type: 2, legalPerson: "黄卫东", licenseNo: null,…},address: "()",bmUserId: "1082611232667623426",bmUserName: "",contact: ""
csUserId: "",csUserName: "陈",enterpriseCode: "z",id: "",legalPerson: "黄东",licenseNo: null,logoUrl: "",name: "",organizationNo: null
phone: "",status: 3,type: 2,yktEnterpriseSn: null
        """
        status=[0,1,2,4,5]
        status = [ 1, 2]
        list = []
        for o in status:
            url="https://%s/api/enterprise/admin/enterprise/page-list?token=%s&status=%s&enterpriseName=&bmUserName=&csUserName=" %  (self.host,self.token,o)
            rows =self.getRowsFromUrl(url)
            list.extend(rows)
        return list

    def get_gasStation_today_turnover(self,id,stationName):
        """
        取得当前油站的营业额
        :param id:
        :param stationName:
        :return: {"stationId":"","stationName":"","orderNumberToday":,"orderNumberYestoday":,"totalAmountToday":.0,"totalAmountYestoday":.04,
        "totalMemberToday":,"totalMemberYestoday":,"effectiveMemberToday":,"effectiveMemberYestoday":,"addMemberToday":0,"addMemberYestoday":49,
        "avePriceYestoday":170,"totalSecondaryMemberToday":29,"totalSecondaryMemberYesterday":27,"addSecondaryMemberToday":0,"addSecondaryMemberYesterday":2}
        """
        url="https://%s/api/enterprise/admin/gas-station/listCount?date=&stationName=%s&token=%s" %  (self.host,stationName,self.token)
        rows = self.getRowsFromUrl(url)

        totalAmountToday = 0
        for o in rows:
            if str(o["stationId"]).__eq__(id):
                if o["totalAmountToday"] is not None:
                    totalAmountToday =o["totalAmountToday"]
        return totalAmountToday

    def is_gasStation_today_turnover_more_than(self,stationId,stationName,money):
        totalAmountToday = self.get_gasStation_today_turnover(stationId,stationName)
        if int(totalAmountToday)>money:
            return True
        return False

    def get_not_online_gasStations(self):
        print('查询没有上线的油站有那些......')
        enterprises = self.get_not_online_enterprises()
        gasStations=[]
        for e in enterprises:
            print(e)
            list = self.get_gasStions_by_enterprise(e["id"],e["name"])
            gasStations.extend(list)
        print(gasStations)
        return gasStations


    def set_has_data_station_to_on_line(self):
        '''
         {"id":"","enterpriseId":"","gasStationCode":"","customerService":"","customerServicePhone":"","customerServiceQrcode":"","enterpriseName":"","name":"","phone":""
        ,"captchePhone":null,"province":"","city":"","area":"","address":"","lng":,"lat":,"status":1,"distance":null,"remainSms":0,"createTime":"","captcheOpenId":null
        ,"memberUserId":null,"yktStationSn":null}
        '''
        gasStations= self.get_not_online_gasStations()
        print('--------------------------------------------')
        print(gasStations)
        list=[]
        for o in gasStations:
            print(o)
            print("查询看：%s 营业额度...." % str(o['name']))
            if self.is_gasStation_today_turnover_more_than(o['id'],o['name'],100):
               print("%s 符合" % o['name'])
               list.append(o['name'])
               info = self.getEnterpriseInfoByGasStationName(o['name'], gasStationId=o['id'])
               info['status']=3


        print("\n\n\n",list)
        return list




def main():
    spide1 = AIYZAdminSpider('robot', 'yjd@1234', "5XDF652CFM7XPIWX6WOBJXAOAKGEZWMZ",);
    spide1.login()
    #spide1.set_has_data_station_to_on_line()
    #spider.getHasDataGasStationsServicer()

    # spider.downloadGasStationInfo()
    # date = datetime.datetime.now() + datetime.timedelta(days=-1)
    # spider.downloadGasStationDayReportWithDayStr_StationName(date,'')


if __name__ == '__main__':
    main()
